package com.fingerth.demo.base

import android.os.Bundle
import android.view.LayoutInflater
import androidx.appcompat.app.AppCompatActivity
import androidx.viewbinding.ViewBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import java.lang.reflect.ParameterizedType
import kotlin.coroutines.CoroutineContext

abstract class BaseAct<T : ViewBinding>() : AppCompatActivity(), CoroutineScope {
    private var _binding: T? = null
    val vBinding: T get() = _binding!!


    private val job: Job by lazy { Job() }

    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Main + job // Activity的协程


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        try {
            (javaClass.genericSuperclass as? ParameterizedType)?.let { _binding = (it.actualTypeArguments[0] as Class<*>).getMethod("inflate", LayoutInflater::class.java).invoke(null, layoutInflater) as T }
        } catch (ex: Exception) {
            ex.printStackTrace()
        }
        if (_binding != null) {
            setContentView(vBinding.root)
            initView()
        }
    }



    override fun onDestroy() {
        super.onDestroy()
        job.cancel() // 关闭页面后，结束所有协程任务
    }

    abstract fun initView()


}